<?php


namespace App\Messenger\Handler;


use App\DTO\CodeInput;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use http\Exception\InvalidArgumentException;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\Translation\Exception\NotFoundResourceException;

class CodeInputHandler implements MessageHandlerInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;
    private $request;

    public function __construct(EntityManagerInterface $entityManager, RequestStack $requestStack)
    {
        $this->entityManager = $entityManager;
        $this->request = $requestStack->getCurrentRequest();
    }

    public function __invoke(CodeInput $input)
    {
        // TODO: Implement __invoke() method.
        $id = $this->request->get('id');
        /** @var User $user */
        $user = $this->entityManager->getRepository(User::class)->find($id);
        if (empty($user)){
            throw new NotFoundResourceException('没有找到数据');
        }
        if (empty($input->getCode())) throw new InvalidArgumentException('请先输入code码');
        /** @var User $Objuser */
        $Objuser = $this->entityManager->getRepository(User::class)->findOneBy(['loveCode' => $input->getCode()]);
        if (empty($Objuser)) throw new NotFoundResourceException('该code码不存在，无效');
        $user->setBindId($Objuser->getId());
        $this->entityManager->persist($user);
        $this->entityManager->flush();

    }

}
